package com.bite.Timer;

import java.util.concurrent.PriorityBlockingQueue;

public class MyTimer {
    private PriorityBlockingQueue<MyTask> queue = new PriorityBlockingQueue<MyTask>();

    private Object locker = new Object();

    public void schedule (Runnable runnable, long delay) {

        MyTask myTask = new MyTask(runnable,delay);
        queue.put(myTask);
        synchronized(locker) {
            locker.notifyAll();
        }
    }

    //定义线程
    MyTimer() {
        Thread thread = new Thread(() -> {
            while (true) {
                try {
                    //获取任务
                    MyTask task = this.queue.take();
                    //看当前时间
                    long currentTime = System.currentTimeMillis();
                    if (currentTime >= task.getTime()) {
                        task.getRunnable().run();
                    } else {
                        queue.put(task);
                        long timeDiff = task.getTime() - currentTime;
                        synchronized(locker) {
                            locker.wait(timeDiff);
                        }
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"scanThread");
        thread.start();
    }
}
